package com.cgq.pro.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.cgq.base.action.BaseAction;
import com.cgq.pro.entity.Ecity;
import com.cgq.pro.entity.Permission;
import com.cgq.pro.entity.User;
import com.cgq.pro.service.EcityService;
import com.cgq.pro.service.PermissionService;
import com.cgq.pro.service.UserService;
import com.cgq.utils.Constants;
import com.cgq.utils.GlobalContext;
import com.cgq.utils.IdGenerator;
import com.cgq.utils.MD5;
import com.opensymphony.xwork2.ActionContext;

/**
 * 控制层组件
 * 用户管理
 * @author chenkaile
 *
 */
@SuppressWarnings("serial")
@Controller
public class UserAction extends BaseAction{
	
	@Autowired
	private UserService userService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private EcityService ecityService;

	/**用户实体*/
	private User model;
	/** 操作方式：增加(add),删除(delete),修改(modify),详情(detail)*/
	private String viewType;
	private List<Permission> permissions;
	/**权限编号*/
	private String perId;
	/**删除数据的id数组*/
	private String ids;
	/**旧密码*/
	private String oldpwd;
	/**新密码*/
	private String newpwd;
	/**确认密码*/
	private String confirmpwd;

	public User getModel() {
		return model;
	}

	public void setModel(User model) {
		this.model = model;
	}
	
	public String getViewType() {
		return viewType;
	}

	public void setViewType(String viewType) {
		this.viewType = viewType;
	}

	public List<Permission> getPermissions() {
		return permissions;
	}

	public void setPermissions(List<Permission> permissions) {
		this.permissions = permissions;
	}
	
	public String getPerId() {
		return perId;
	}

	public void setPerId(String perId) {
		this.perId = perId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getOldpwd() {
		return oldpwd;
	}

	public void setOldpwd(String oldpwd) {
		this.oldpwd = oldpwd;
	}

	public String getNewpwd() {
		return newpwd;
	}

	public void setNewpwd(String newpwd) {
		this.newpwd = newpwd;
	}

	public String getConfirmpwd() {
		return confirmpwd;
	}

	public void setConfirmpwd(String confirmpwd) {
		this.confirmpwd = confirmpwd;
	}

	/**
	 * 用户列表界面
	 * @return
	 */
	public String toList(){
		permissionId=getCurrentUser().getPerId().getPerFlag();
		return GlobalContext.RESULT_LIST_UI;
	}
	
	/**
	 * 增删改界面
	 * @return
	 */
	public String toForm(){
		permissions=permissionService.findAll();
		if(GlobalContext.RESULT_ADD.equals(viewType)){
			model=new User();
		}else{
			model=userService.find(model.getId());
		}
		return GlobalContext.RESULT_FORM_UI;
	}
	
	/**
	 * 保存数据
	 * @throws Exception 
	 */
	public void save() throws Exception{
		try {
			Date currentDate=new Date();
			
			model.setPerId(permissionService.find(perId));
			if(GlobalContext.RESULT_ADD.equals(viewType))//保存
			{
				model.setId(IdGenerator.getId(service,Constants.TABLE_USER, Constants.PREFIX_USER, 10));
				model.setDateCre(currentDate);
				model.setPassword(MD5.MD5Encode("123456"));
				model.setUserCre(getCurrentUser().getName());
				userService.save(model);
				ajaxDoneSuccess("保存成功");
			}else{
				model.setDateUpd(currentDate);
				model.setUserUpd(getCurrentUser().getName());
				userService.update(model);
				ajaxDoneSuccess("更新成功");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			ajaxDoneSuccess("保存失败");
		}
	}
	
	/**
	 * 获取数据列表
	 * @return
	 */
	public String getAllRecords(){
		//当前页  
		int intPage = Integer.parseInt((page == null || page == "0") ? "1":page);  
		//每页显示条数  
		int number = Integer.parseInt((rows == null || rows == "0") ? "5":rows);  
		//每页的开始记录  第一页为1  第二页为number +1   
		int start = (intPage-1)*number;

		Map<String, String> map=null;

		int total=userService.getTotal(map);

		List<User> list=userService.getAllRecords(start, number, map);
		List<Map<String, Object>> maps=new ArrayList<Map<String,Object>>();
		for (User city : list) {
			maps.add(city.toMap());
		}
		Map<String, Object> json = new HashMap<String, Object>(); 
		json.put("total", total);
		json.put("rows", maps);
		resultObj =JSONObject.fromObject(json);
		return "success";
	}
	
	/**
	 * 验证用户名和密码是否正确 
	 */
	public void isLogin()
	{
		model.setPassword(MD5.MD5Encode(model.getPassword()));
		model=userService.findUserByNameAndPwd(model);
		if(model!=null){
			//将当前登录用户保存到session中
			ActionContext.getContext().getSession().put(Constants.USER_SESSION, model);
			ajaxDoneSuccess();
		}else{
			ajaxDoneError("用户名或密码输入不正确！");
		}
	}
	
	/**
	 * 主页
	 * @return
	 */
	public String toMain()
	{
		ecity=ecityService.getCurrentCity();
		return "mainUI";
	}

	/**
	 * 登陆界面
	 * @return
	 */
	public String login(){
		return "loginUI";
	}
	
	
	/**
	 * 修改密码
	 */
	public void updatepwd(){
		User user=getCurrentUser();
		if(!user.getPassword().equals(MD5.MD5Encode(oldpwd))){
			ajaxDoneError("旧密码输入不正确,请重新输入");
			return;
		}
		
		if( !newpwd.equals(confirmpwd)){
			ajaxDoneError("两次密码输入不正确,请重新输入");
			return;
		}
		try {
			user.setPassword(MD5.MD5Encode(newpwd));
			userService.update(user);
			ajaxDoneSuccess("修改密码成功,请重新登陆");
		} catch (Exception e) {
			ajaxDoneError("修改密码失败");
		}
		
	}
	
	/**
	 * 删除
	 * @throws Exception
	 */
	public void delete() throws Exception{
		try {
			String[] idList=ids.split(",");
			userService.delete(idList);
			ajaxDoneSuccess("删除成功");
		} catch (Exception e) {
			ajaxDoneSuccess("删除失败");
		}
	}
	
	/**
	 * 跳转到修改密码的界面
	 * @return
	 */
	public String toChangePwdForm(){
		return "changePwdUI";
	}
	
	/**
	 * 退出方法
	 * @return
	 */
	public String logout(){
		//移除session
		ActionContext.getContext().getSession().remove(Constants.USER_SESSION);
		ActionContext.getContext().getSession().clear();
		return "loginUI";
	}
	
}
